package com.wangy.test.jdkProxy.impl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.wangy.test.jdkProxy.Interceptor;

public class InterceptorJDKProxy implements InvocationHandler {
	
	private Object target;	//真实对象

	private String interceptorClass = null;	//拦截器的全限定名
	
	public InterceptorJDKProxy(Object target, String interceptorClass) {
		this.target = target;
		this.interceptorClass = interceptorClass;
	}
	
	public static Object bind(Object target, String interceptorClass) {
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InterceptorJDKProxy(target, interceptorClass));
	}
	
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		if(this.interceptorClass == null) {
			return method.invoke(target, args);
		}
		Object result = null;
		Interceptor interceptor = (Interceptor) Class.forName(this.interceptorClass).newInstance();
		if(interceptor.before(proxy, target, method, args)) {
			result = method.invoke(target, args);
		}else {
			interceptor.around(proxy, target, method, args);
		}
		interceptor.after(proxy, target, method, args);
		return result;
	}

}
